import json


from dotenv import load_dotenv
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from database.database import get_db
from models.custom_history import CustomHistory

load_dotenv()

router = APIRouter()

KEY_MAPPING = {
    "range_": "优势射程",
    "recoil": "后坐力控制",
    "speed": "操控速度",
    "stability": "据枪稳定性",
    "hipAccuracy": "腰际射击精度",
    "param_weights": "性能权重",
    "add_values": "性能要求",
    "price_range": "价格范围",
    "must_have_part": "必须有的部位",
    "must_not_have_part": "必须没有的部位",
    "must_have_accessory": "必须有的配件",
    "must_not_have_accessory": "必须没有的配件",
    "min_": "最小值",
    "max_": "最大值",
}

@router.get("/history/", tags=["custom"])
async def get_history(open_id: str=Query(), db: Session=Depends(get_db)):
    # open_id = user.open_id
    history = db.query(CustomHistory).filter(CustomHistory.open_id==open_id).order_by(CustomHistory.create_time.desc()).all()
    result = []
    for item in history:
        condition = {}
        for key, value in item.condition.items():
            if key == "gun":
                condition["枪械"] = value
                continue
            if key in ["must_have_part", "must_not_have_part", "must_have_accessory", "must_not_have_accessory"]:
                condition[KEY_MAPPING[key]] = value
                continue 
            condition[KEY_MAPPING[key]] = {}
            for k, v in value.items():
                if key == "add_values" and v == -100.0:
                    condition[KEY_MAPPING[key]][KEY_MAPPING[k]] = 0
                else:
                    condition[KEY_MAPPING[key]][KEY_MAPPING[k]] = v
        result.append({
           "条件": condition,
           "结果": item.result, 
           "创建时间": item.create_time.strftime("%Y-%m-%d %H:%M:%S")
        })
    return result